﻿using System;
using System.Windows.Forms;
using monitor_2_DBwork;

namespace monitor_server_2
{
    //public delegate string OKAddUserDelegate(string l, string p, string a, string i);
    //public delegate void cancelAddUserDelegate();
        

    public partial class AccessList : Form
    {
        public delegate void OkAddUserDelegate(string l, string p, string a, string i, bool newUser);
        bool _success, _loginSuccess;



        public enum AccessType
        {
            Администратор = 1,
            Пользователь = 2
        }

        /*class User
        {
            string _login;
            byte _access;
            string _info;
        }

        List<User> Users = new List<User>();*/

        public AccessList()
        {
            InitializeComponent();
        }

        private void AccessList_Load(object sender, EventArgs e)
        {
            _loginSuccess = new LoginForm(LoginForm.AccessType.Admin).ShowDialog() == DialogResult.Yes;
            //_loginSuccess = true;
            if (!_loginSuccess)
                return;
            МенюToolStripMenuItem.Text = Main.Rm.GetString("Menu");
            выходToolStripMenuItem.Text = Main.Rm.GetString("Close");
            добавитьпользователяToolStripMenuItem.Text = Main.Rm.GetString("AddUser");
            usersList.View = View.Details;
            usersList.GridLines = true;
            usersList.HeaderStyle = ColumnHeaderStyle.Clickable;
            usersList.FullRowSelect = true;
            usersList.Columns.Add(Main.Rm.GetString("UserName"));
            usersList.Columns[usersList.Columns.Count - 1].Width = 120;
            usersList.Columns.Add(Main.Rm.GetString("Access"));
            usersList.Columns[usersList.Columns.Count - 1].Width = 100;
            usersList.Columns.Add(Main.Rm.GetString("AdditionalInfo"));
            usersList.Columns[usersList.Columns.Count - 1].Width = 180;
            RefreshList();
        }

        private void RefreshList()
        {
            var colls = new ColumnHeader[usersList.Columns.Count];
            int j = 0;
            foreach (ColumnHeader col in usersList.Columns)
            {
                colls[j++] = col;
            }

            usersList.Clear();

            usersList.Columns.AddRange(colls);
            string usersStr;
            try
            {
                usersStr = DBwork.GetUsers();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Main.Rm.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                _success = false;
                return;
            }
            if (usersStr.Contains("err:"))
            {
                MessageBox.Show(usersStr.Substring(4), Main.Rm.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                _success = false;
                return;
            }

            string[] split = usersStr.Split(';');
            //List<ListViewItem> items = new List<ListViewItem>();
            usersList.BeginUpdate();
            foreach (string str in split)
            {
                if (str.Length < 1)
                    continue;
                string[] splitik = str.Split(':');
                var item = new ListViewItem(splitik[0]);
                for (int i = 1; i < splitik.Length; i++)
                {
                    item.SubItems.Add(splitik[i]);
                }
                usersList.Items.Add(item);
            }
            usersList.EndUpdate();
            _success = true;
        }           //Обновить лист

        private void выходToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void добавитьпользователяToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _success = false;
            var addUserForm = new MyForm();
            OkAddUserDelegate del = AccessList_UpdateUserEvent;
            var newAddUserForm = new AddUser(d: del, newser: true, data: "") {Owner = this};
            addUserForm.SetForm = newAddUserForm;
            if (newAddUserForm.ShowDialog() == DialogResult.OK)
                if (_success)
                {
                    MessageBox.Show(Main.Rm.GetString("Complete"));
                    RefreshList();
                }
                else
                {
                    MessageBox.Show(Main.Rm.GetString("Error"));
                }

        }

        void AccessList_UpdateUserEvent(string l, string p, string a, string i, bool newUser)
        {
            var str = newUser ? DBwork.CallMethod("AddUser", l, p, a, i) : DBwork.CallMethod("DelUser", l);
            if (str == "ok")
                _success = true;
        }

        private void usersList_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            var list = (ListView)sender;
            if (e.Button != MouseButtons.Left)
                return;
            ListViewItem lvitem = list.FocusedItem;
            string data = "";
            data += lvitem.Text + ';';
            data += (int)(Enum.Parse(typeof(AccessType), lvitem.SubItems[1].Text, true)) + ";";
            data += lvitem.SubItems[2].Text;

            _success = false;
            var addUserForm = new MyForm();
            OkAddUserDelegate del = AccessList_UpdateUserEvent;
            var newAddUserForm = new AddUser(d: del, newser: false, data: data) {Owner = this};
            addUserForm.SetForm = newAddUserForm;

            if (newAddUserForm.ShowDialog() == DialogResult.OK)
                if (_success)
                {
                    MessageBox.Show(Main.Rm.GetString("Complete"));
                    RefreshList();
                }
                else
                {
                    MessageBox.Show(Main.Rm.GetString("Error"));
                }

        }

        private void AccessList_Shown(object sender, EventArgs e)
        {
            if (!_success || !_loginSuccess)
                Close();
        }

        
    }
}
